package com.csdj.rest.service;

import com.csdj.beans.entity.Config;
import com.csdj.beans.entity.ConfigExample;
import com.csdj.common.constant.CacheConstant;
import com.csdj.rest.mapper.ConfigMapper;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@CacheConfig(cacheNames = CacheConstant.CACHE_CONFIG)
public class ConfigService {

    @Resource
    private ConfigMapper configMapper;

    @CachePut(keyGenerator = "keyGenerator")
    public Config addConfig(Config config){
        if(configMapper.insert(config)>0)return config;
        return null;
    }

    @Cacheable(key = "#root.methodName+#type+#key")
    public Config getConfig(String type,String key){
        System.out.println("从数据库中查找");
        final ConfigExample configExample = new ConfigExample();
        configExample.createCriteria().andTypeEqualTo(type).andKeyEqualTo(key);
        Config config = configMapper.selectOneByExample(configExample);
        return config;
    }

    @CacheEvict(key = "#config.type+#config.key",allEntries = true)
    public boolean update(Config config){
        return configMapper.updateByPrimaryKeySelective(config)>0;
    }

    public List<Config> getByPage(int page,int rows){
        int index = (page-1)*rows;
        ConfigExample example = new ConfigExample();
        example.setLimit(rows);
        example.setOffset(index);
        return configMapper.selectByExample(example);
    }
    public long getCount(){
        return configMapper.countByExample(new ConfigExample());
    }
}
